import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {AppGlobal, AppService} from "../../../services/app.service";
import {Storage} from "@ionic/storage";
import {ResDataModel} from "../../../models/res-data-model";
import {UserInfoService} from "../../../services/userInfo.service";

/**
 * Generated class for the GetIdentifyingCodePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-get-identifying-code',
  templateUrl: 'get-identifying-code.html',
})
export class GetIdentifyingCodePage {

  mail:string = "";
  identifyingCode:string = "";
  mailSended:boolean = false;//是否发送过邮件
  seconds:number;
  device:any;//设备信息
  login:boolean = false;//是否需要登录
  timer:any;//局部计时器

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private appService:AppService,
              private storage:Storage,
              private userInfoService:UserInfoService) {
    this.device = this.navParams.get("device");
    this.login = this.navParams.get("login");
    if(!this.login){
      this.mail = this.hideMailString(this.userInfoService.user.mail);
    }

    this.seconds = AppGlobal.seconds;
    if(this.seconds<60){
      //初始化一个定时器，只修改局部变量
      this.timer = setInterval(()=>{
        this.seconds = this.seconds - 1;
        if(this.seconds == 0){
          //重置为60s
          this.seconds = 60;
          clearInterval(this.timer);
        }
      },1000)
    }
  }

  ionViewDidLoad() {
  }

  ionViewDidLeave(){
    //离开页面时清除局部计时器
    clearInterval(this.timer);
  }
  /**
   * 获取验证码（邮箱发送）
   */
  getIdentifyingCode(){
    //60s倒计时
    AppGlobal.seconds --;
    this.seconds = AppGlobal.seconds;
    //定时器，修改全局计时变量
    var interval = setInterval(()=>{
      AppGlobal.seconds = AppGlobal.seconds - 1;
      this.seconds = AppGlobal.seconds;
      if(AppGlobal.seconds == 0){
        //重置为60s
        AppGlobal.seconds = 60;
        this.seconds = AppGlobal.seconds;
        clearInterval(interval);
      }
    },1000);

    this.appService.httpPost('AppUserCtrl_sendIdentifyingCodeForResetPassword',
      {mail:this.mail},null,(res:ResDataModel)=>{
        if(res.datas[0].value=="success"){
          //标志改为已发送
          this.mailSended = true;
          this.appService.smallToast('验证码已发送')
        }
      },false)
  }

  /**
   * 跳转修改密码页面
   */
  toModifyPasswordPage(){
    if(this.login){//需要登录
      //构造请求参数
      let postData = {
        mail:this.mail,
        identifyingCode:this.identifyingCode,
        position:{
          lng:AppGlobal.longitude.toString(),
          lat:AppGlobal.latitude.toString()
        },
        device:this.device
      }
      //进行验证码登录操作
      this.appService.httpPost('AppLoginCtrl_loginWithIdentifyingCode',
        postData,null,(res:ResDataModel)=>{
          let flag = res.getAttr('flag');
          if (flag == 'success') {//登录成功
            //记下token
            let token = res.getAttr('token')
            console.log('token:'+token);
            this.storage.set('token', token);
            AppGlobal.token = token;
            //跳转
            this.navCtrl.push('ModifyPasswordPage');
          }
        },true)
    } else { //不需要登录
      //构造请求参数
      let postData = {
        mail:this.userInfoService.user.mail,
        identifyingCode:this.identifyingCode,
      }
      this.appService.httpPost('AppUserCtrl_checkModifyPasswordIdentifyingCode',postData,null,(res:ResDataModel)=>{
        let flag = res.getAttr('flag');
        if (flag == 'success') {//登录成功
          //跳转
          this.navCtrl.push('ModifyPasswordPage');
        }
      },true);
    }

  }

  /**
   * 隐藏邮箱地址的部分字符串
   * @param {string} mail
   * @returns {string}
   */
  hideMailString(mail:string):string{
    var nameString = mail.substring(0,mail.indexOf('@'));
    if(nameString.length>3){
      nameString = nameString.substr(0,3)+"*".repeat(nameString.length-3);
    }
    return nameString + mail.substring(mail.indexOf('@'));
  }
}
